package com.zx.security.block.handle;

import com.alibaba.fastjson2.JSON;
import com.zx.core.wrapper.ResponseWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;

/**
 * <p>
 * description: 认证失败处理类, 返回未授权 <br>
 * create: 2024-08-21 00:15
 * </p>
 *
 * @author zhou  xun
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response, AuthenticationException e)
            throws IOException {

        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("utf-8");
        //设置返回消息
        ResponseWrapper result = new ResponseWrapper();
        result.fail(String.format("请求访问:%s，认证失败，无法访问系统资源", request.getRequestURI()));
        response.getWriter().print(JSON.toJSONString(result));
    }
}
